﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "权限管理";
    Layout = null;
}

<!-- 引入layui CSS -->
<link rel="stylesheet" href="https://unpkg.com/layui@2.6.8/dist/css/layui.css">

<style>
    .permission-container {
        height: 100vh;
        padding: 10px;
        background-color: #f5f5f5;
    }
    .permission-left {
        background-color: #fff;
        border-radius: 4px;
        padding: 15px;
        height: calc(100vh - 40px);
        overflow-y: auto;
    }
    .permission-right {
        background-color: #fff;
        border-radius: 4px;
        padding: 15px;
        height: calc(100vh - 40px);
        overflow-y: auto;
    }
    .tree-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 15px;
        color: #333;
        border-bottom: 1px solid #e6e6e6;
        padding-bottom: 10px;
    }
    .form-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 15px;
        color: #333;
        border-bottom: 1px solid #e6e6e6;
        padding-bottom: 10px;
    }
    .layui-tree-txt {
        cursor: pointer;
    }
    .layui-tree-txt:hover {
        color: #1E9FFF;
    }
    .current-node {
        background-color: #f2f9ff;
        color: #1E9FFF !important;
        border-radius: 2px;
        padding: 2px 5px;
    }
</style>

<div class="permission-container">
    <div class="layui-row layui-col-space10">
        <!-- 左侧权限树 -->
        <div class="layui-col-md4">
            <div class="permission-left">
                <div class="tree-title">
                    <i class="layui-icon layui-icon-tree"></i> 权限树形结构
                </div>
                <div id="permissionTree"></div>
            </div>
        </div>
        
        <!-- 右侧权限表单 -->
        <div class="layui-col-md8">
            <div class="permission-right">
                <div class="form-title">
                    <i class="layui-icon layui-icon-form"></i> 权限信息
                    <button class="layui-btn layui-btn-xs layui-btn-primary" id="initDataBtn" style="float: right;">
                        <i class="layui-icon layui-icon-addition"></i> 初始化测试数据
                    </button>
                </div>
                
                <!-- 权限表单 -->
                <form class="layui-form" lay-filter="permissionForm" id="permissionForm">
                    <input type="hidden" name="Id" id="permissionId" value="0">
                    
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="width: 100px;">权限名称</label>
                                <div class="layui-input-block" style="margin-left: 130px;">
                                    <input type="text" name="PermissionName" lay-verify="required" placeholder="请输入权限名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="width: 100px;">权限父级ID</label>
                                <div class="layui-input-block" style="margin-left: 130px;">
                                    <input type="number" name="FatherPermissionId" value="0" placeholder="请输入父级权限ID" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="width: 100px;">父级权限名称</label>
                                <div class="layui-input-block" style="margin-left: 130px;">
                                    <input type="text" name="FatherPermissionName" placeholder="父级权限名称（自动显示）" autocomplete="off" class="layui-input" readonly style="background-color: #f5f5f5;">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="width: 100px;">权限路径</label>
                                <div class="layui-input-block" style="margin-left: 130px;">
                                    <input type="text" name="PermissionPath" placeholder="请输入权限路径" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="width: 100px;">排序ID</label>
                                <div class="layui-input-block" style="margin-left: 130px;">
                                    <input type="number" name="OrderId" value="0" placeholder="请输入排序ID" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="width: 100px;">权限图标</label>
                                <div class="layui-input-block" style="margin-left: 130px;">
                                    <input type="text" name="PermissionImg" placeholder="请输入权限图标" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="width: 100px;">权限状态</label>
                                <div class="layui-input-block" style="margin-left: 130px;">
                                    <input type="checkbox" name="PermissionState" lay-skin="switch" lay-text="启用|禁用" checked>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                
                <!-- 操作按钮区域 -->
                <div class="layui-form-item" style="margin-top: 30px;">
                    <div class="layui-input-block">
                        <button class="layui-btn" id="saveBtn">
                            <i class="layui-icon layui-icon-ok"></i> 保存
                        </button>
                        <button class="layui-btn layui-btn-normal" id="addSiblingBtn">
                            <i class="layui-icon layui-icon-add-1"></i> 添加同级
                        </button>
                        <button class="layui-btn layui-btn-warm" id="addChildBtn">
                            <i class="layui-icon layui-icon-add-circle"></i> 添加子级
                        </button>
                        <button class="layui-btn layui-btn-danger" id="clearBtn">
                            <i class="layui-icon layui-icon-refresh-1"></i> 清空
                        </button>
                        <button class="layui-btn layui-btn-primary" id="refreshTreeBtn">
                            <i class="layui-icon layui-icon-refresh"></i> 刷新树
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 引入layui JS -->
<script src="https://unpkg.com/layui@2.6.8/dist/layui.js"></script>

<script>
layui.use(['form', 'layer', 'tree'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var tree = layui.tree;
    
    var currentNodeId = 0; // 当前选中的节点ID
    var currentNodeData = null; // 当前选中的节点数据
    
    // 初始化加载权限树
    loadPermissionTree();
    
    /**
     * 加载权限树
     */
    function loadPermissionTree() {
        console.log('开始加载权限树...');
        
        fetch('@Url.Action("GetPermissionTree", "RBAC")', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => {
            console.log('响应状态:', response.status);
            console.log('响应头:', response.headers);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            return response.text(); // 先获取文本，然后手动解析JSON
        })
        .then(text => {
            console.log('响应内容:', text);
            
            if (!text || text.trim() === '') {
                throw new Error('响应为空');
            }
            
            let result;
            try {
                result = JSON.parse(text);
            } catch (e) {
                console.error('JSON解析失败:', e);
                throw new Error('JSON解析失败: ' + text);
            }
            
            if (result.success && result.data) {
                console.log('权限树数据:', result.data);
                renderTree(result.data);
            } else {
                console.warn('权限树数据为空，可能需要初始化数据');
                if (result.data && result.data.length === 0) {
                    layer.msg('暂无权限数据，请点击"初始化测试数据"按钮', {icon: 0, time: 3000});
                    renderTree([]); // 渲染空树
                } else {
                    layer.msg(result.message || '加载权限树失败', {icon: 2});
                }
            }
        })
        .catch(error => {
            console.error('加载权限树出错:', error);
            layer.msg('网络错误或服务器错误: ' + error.message, {icon: 2, time: 5000});
        });
    }
    
    /**
     * 渲染权限树
     */
    function renderTree(data) {
        tree.render({
            elem: '#permissionTree',
            data: data,
            showCheckbox: false,
            id: 'permissionTreeReload',
            isJump: true,
            click: function(obj) {
                console.log('点击树节点:', obj.data);
                
                // 移除之前的高亮
                $('.current-node').removeClass('current-node');
                // 高亮当前节点
                $(obj.elem).find('.layui-tree-txt').first().addClass('current-node');
                
                currentNodeId = obj.data.id;
                currentNodeData = obj.data;
                
                // 更新表单标题
                updateFormTitle(obj.data.title || obj.data.name || '未知权限');
                
                // 加载权限详情到表单
                loadPermissionToForm(obj.data.id);
            }
        });
    }
    
    /**
     * 更新表单标题显示当前编辑的权限
     */
    function updateFormTitle(permissionName) {
        var formTitle = document.querySelector('.form-title');
        if (formTitle) {
            formTitle.innerHTML = `
                <i class="layui-icon layui-icon-form"></i> 权限信息 - 当前编辑: <span style="color: #1E9FFF;">${permissionName}</span>
                <button class="layui-btn layui-btn-xs layui-btn-primary" id="initDataBtn" style="float: right;">
                    <i class="layui-icon layui-icon-addition"></i> 初始化测试数据
                </button>
            `;
            
            // 重新绑定初始化按钮事件
            bindInitDataBtnEvent();
        }
    }
    
    /**
     * 重置表单标题
     */
    function resetFormTitle() {
        var formTitle = document.querySelector('.form-title');
        if (formTitle) {
            formTitle.innerHTML = `
                <i class="layui-icon layui-icon-form"></i> 权限信息
                <button class="layui-btn layui-btn-xs layui-btn-primary" id="initDataBtn" style="float: right;">
                    <i class="layui-icon layui-icon-addition"></i> 初始化测试数据
                </button>
            `;
            
            // 重新绑定初始化按钮事件
            bindInitDataBtnEvent();
        }
    }
    
    /**
     * 加载权限详情到表单
     */
    function loadPermissionToForm(permissionId) {
        console.log('开始加载权限详情到表单，ID:', permissionId);
        
        if (!permissionId || permissionId <= 0) {
            console.warn('权限ID无效:', permissionId);
            return;
        }
        
        var loadingIndex = layer.load(2, {
            shade: [0.1, '#fff']
        });
        
        fetch('@Url.Action("GetPermissionDetailById", "RBAC")?id=' + permissionId, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => {
            console.log('权限详情API响应状态:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            layer.close(loadingIndex);
            console.log('权限详情API响应结果:', result);
            
            if (result.success && result.data) {
                fillForm(result.data);
                layer.msg('权限信息加载成功', {icon: 1, time: 1500});
            } else {
                layer.msg(result.message || '获取权限详情失败', {icon: 2});
                console.error('获取权限详情失败:', result.message);
            }
        })
        .catch(error => {
            layer.close(loadingIndex);
            console.error('加载权限详情出错:', error);
            layer.msg('网络错误，请稍后重试: ' + error.message, {icon: 2});
        });
    }
    
    /**
     * 填充表单数据
     */
    function fillForm(permissionDetail) {
        console.log('开始填充表单数据:', permissionDetail);
        
        try {
            // 填充基础字段
            document.getElementById('permissionId').value = permissionDetail.id || 0;
            document.querySelector('input[name="PermissionName"]').value = permissionDetail.permissionName || '';
            document.querySelector('input[name="FatherPermissionId"]').value = permissionDetail.fatherPermissionId || 0;
            document.querySelector('input[name="FatherPermissionName"]').value = permissionDetail.fatherPermissionName || '';
            document.querySelector('input[name="PermissionPath"]').value = permissionDetail.permissionPath || '';
            document.querySelector('input[name="OrderId"]').value = permissionDetail.orderId || 0;
            document.querySelector('input[name="PermissionImg"]').value = permissionDetail.permissionImg || '';
            
            // 设置权限状态复选框
            var permissionStateCheckbox = document.querySelector('input[name="PermissionState"]');
            if (permissionStateCheckbox) {
                permissionStateCheckbox.checked = permissionDetail.permissionState !== false;
            }
            
            // 重新渲染layui表单组件
            form.render();
            
            console.log('表单数据填充完成');
            
            // 显示父级权限信息（如果有）
            if (permissionDetail.fatherPermissionName && permissionDetail.fatherPermissionId > 0) {
                layer.msg('当前权限父级: ' + permissionDetail.fatherPermissionName, {icon: 1, time: 2000});
            }
            
        } catch (error) {
            console.error('填充表单数据时出错:', error);
            layer.msg('填充表单数据失败: ' + error.message, {icon: 2});
        }
    }
    
    /**
     * 清空表单
     */
    function clearForm() {
        document.getElementById('permissionId').value = '0';
        document.querySelector('input[name="PermissionName"]').value = '';
        document.querySelector('input[name="FatherPermissionId"]').value = '0';
        document.querySelector('input[name="FatherPermissionName"]').value = '';
        document.querySelector('input[name="PermissionPath"]').value = '';
        document.querySelector('input[name="OrderId"]').value = '0';
        document.querySelector('input[name="PermissionImg"]').value = '';
        document.querySelector('input[name="PermissionState"]').checked = true;
        
        form.render();
        
        // 重置表单标题
        resetFormTitle();
    }
    
    /**
     * 获取表单数据
     */
    function getFormData() {
        return {
            Id: parseInt(document.getElementById('permissionId').value) || 0,
            PermissionName: document.querySelector('input[name="PermissionName"]').value,
            FatherPermissionId: parseInt(document.querySelector('input[name="FatherPermissionId"]').value) || 0,
            FatherPermissionName: document.querySelector('input[name="FatherPermissionName"]').value,
            PermissionPath: document.querySelector('input[name="PermissionPath"]').value,
            OrderId: parseInt(document.querySelector('input[name="OrderId"]').value) || 0,
            PermissionImg: document.querySelector('input[name="PermissionImg"]').value,
            PermissionState: document.querySelector('input[name="PermissionState"]').checked
        };
    }
    
    // 保存按钮事件
    document.getElementById('saveBtn').addEventListener('click', function(){
        var data = getFormData();
        
        // 验证必填字段
        if (!data.PermissionName.trim()) {
            layer.msg('请输入权限名称', {icon: 5});
            return;
        }
        
        // 显示确认对话框
        var actionText = data.Id > 0 ? '修改' : '添加';
        layer.confirm('确定要' + actionText + '这个权限吗？', {
            btn: ['确定', '取消']
        }, function(index) {
            // 调用后端API保存数据
            fetch('@Url.Action("SavePermission", "RBAC")', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    layer.msg(result.message, {icon: 1});
                    // 刷新权限树
                    loadPermissionTree();
                    // 如果是新增，更新表单中的ID
                    if (data.Id === 0 && result.data) {
                        document.getElementById('permissionId').value = result.data;
                    }
                } else {
                    layer.msg(result.message || '操作失败', {icon: 2});
                }
            })
            .catch(error => {
                console.error('Error:', error);
                layer.msg('网络错误，请稍后重试', {icon: 2});
            });
            
            layer.close(index);
        });
    });
    
    // 添加同级按钮事件
    document.getElementById('addSiblingBtn').addEventListener('click', function(){
        if (currentNodeId === 0) {
            // 如果没有选中节点，创建根节点
            clearForm();
            layer.msg('准备添加根级权限', {icon: 1});
        } else {
            // 获取当前节点的父级ID
            var currentFatherPermissionId = document.querySelector('input[name="FatherPermissionId"]').value;
            
            // 清空表单但保持父级ID不变
            clearForm();
            document.querySelector('input[name="FatherPermissionId"]').value = currentFatherPermissionId;
            
            form.render();
            layer.msg('准备添加同级权限', {icon: 1});
        }
    });
    
    // 添加子级按钮事件
    document.getElementById('addChildBtn').addEventListener('click', function(){
        if (currentNodeId === 0) {
            layer.msg('请先选择一个权限节点', {icon: 5});
            return;
        }
        
        var currentName = document.querySelector('input[name="PermissionName"]').value;
        
        // 将当前权限ID设为父级ID
        clearForm();
        document.querySelector('input[name="FatherPermissionId"]').value = currentNodeId;
        
        form.render();
        layer.msg('准备为 "' + currentName + '" 添加子级权限', {icon: 1});
    });
    
    // 清空按钮事件
    document.getElementById('clearBtn').addEventListener('click', function(){
        clearForm();
        currentNodeId = 0;
        currentNodeData = null;
        
        // 移除树节点高亮
        $('.current-node').removeClass('current-node');
        
        layer.msg('表单已清空', {icon: 1});
    });
    
    // 刷新树按钮事件
    document.getElementById('refreshTreeBtn').addEventListener('click', function(){
        loadPermissionTree();
        layer.msg('权限树已刷新', {icon: 1});
    });
    
    // 绑定初始化数据按钮事件
    function bindInitDataBtnEvent() {
        var initBtn = document.getElementById('initDataBtn');
        if (initBtn) {
            initBtn.removeEventListener('click', initDataClickHandler);
            initBtn.addEventListener('click', initDataClickHandler);
        }
    }
    
    /**
     * 初始化数据按钮点击事件处理函数
     */
    function initDataClickHandler() {
        layer.confirm('确定要初始化测试权限数据吗？<br>这将创建系统管理、生产系统、人力资源等示例权限。', {
            btn: ['确定', '取消'],
            title: '初始化权限数据'
        }, function(index) {
            var loadingIndex = layer.load(1, {
                shade: [0.1, '#fff']
            });
            
            fetch('@Url.Action("InitTestPermissions", "RBAC")', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(result => {
                layer.close(loadingIndex);
                if (result.success) {
                    layer.msg(result.message, {icon: 1, time: 3000});
                    // 初始化成功后重新加载权限树
                    setTimeout(function() {
                        loadPermissionTree();
                    }, 1000);
                } else {
                    layer.msg(result.message || '初始化失败', {icon: 2});
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error('初始化数据出错:', error);
                layer.msg('网络错误: ' + error.message, {icon: 2});
            });
            
            layer.close(index);
        });
    }
    
    // 页面加载时绑定初始化数据按钮事件
    bindInitDataBtnEvent();
});
</script>
